{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "33adcdb3",
   "metadata": {},
   "source": [
    "# Video Detection Demo with PytorchWildlife"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c534c504",
   "metadata": {},
   "source": [
    "This tutorial guides you on how to use PyTorchWildlife for video detection and classification. We will go through the process of setting up the environment, defining the detection and classification models, as well as performing inference and saving the results in an annotated video.\n",
    "\n",
    "## Prerequisites\n",
    "Install PytorchWildlife running the following commands:\n",
    "```bash\n",
    "conda create -n pytorch_wildlife python=3.10 -y\n",
    "conda activate pytorch_wildlife\n",
    "pip install PytorchWildlife\n",
    "```\n",
    "Also, make sure you have a CUDA-capable GPU if you intend to run the model on a GPU. This notebook can also run on CPU.\n",
    "\n",
    "## Importing libraries\n",
    "First, let's import the necessary libraries and modules."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a28c392c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import supervision as sv\n",
    "import torch\n",
    "from PytorchWildlife.models import detection as pw_detection\n",
    "from PytorchWildlife.models import classification as pw_classification\n",
    "from PytorchWildlife import utils as pw_utils"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "802747c2",
   "metadata": {},
   "source": [
    "## Model Initialization\n",
    "We'll  define the device to run the models and then we will initialize the models for both video detection and classification."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dd069110",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Setting the device to use for computations ('cuda' indicates GPU)\n",
    "DEVICE = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "if DEVICE == \"cuda\":\n",
    "    torch.cuda.set_device(0)\n",
    "SOURCE_VIDEO_PATH = os.path.join(\".\",\"demo_data\",\"videos\",\"opossum_example.MP4\")\n",
    "TARGET_VIDEO_PATH = os.path.join(\".\",\"demo_data\",\"videos\",\"opossum_example_processed.MP4\")\n",
    "\n",
    "# Initializing the MegaDetectorV6 model for image detection\n",
    "# Valid versions are MDV6-yolov9-c, MDV6-yolov9-e, MDV6-yolov10-c, MDV6-yolov10-e or MDV6-rtdetr-c\n",
    "detection_model = pw_detection.MegaDetectorV6(device=DEVICE, pretrained=True, version=\"MDV6-yolov10-e\")\n",
    "\n",
    "# Uncomment the following line to use MegaDetectorV5 instead of MegaDetectorV6\n",
    "#detection_model = pw_detection.MegaDetectorV5(device=DEVICE, pretrained=True, version=\"a\")\n",
    "\n",
    "# Initializing the AI4GOpossum model for image classification\n",
    "classification_model = pw_classification.AI4GOpossum(device=DEVICE, pretrained=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3cd6262a",
   "metadata": {},
   "source": [
    "## Video Processing\n",
    "For each frame in the video, we'll apply detection and classification, and then annotate the frame with the results. The processed video will be saved with annotated detections and classifications."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "e6147a40",
   "metadata": {},
   "outputs": [],
   "source": [
    "box_annotator = sv.BoxAnnotator(thickness=4)\n",
    "lab_annotator = sv.LabelAnnotator(text_color=sv.Color.BLACK, text_thickness=4, text_scale=2)\n",
    "\n",
    "def callback(frame: np.ndarray, index: int) -> np.ndarray:\n",
    "    results_det = detection_model.single_image_detection(frame, img_path=index)\n",
    "    labels = []\n",
    "    for xyxy in results_det[\"detections\"].xyxy:\n",
    "        cropped_image = sv.crop_image(image=frame, xyxy=xyxy)\n",
    "        results_clf = classification_model.single_image_classification(cropped_image)\n",
    "        labels.append(\"{} {:.2f}\".format(results_clf[\"prediction\"], results_clf[\"confidence\"]))\n",
    "    annotated_frame = lab_annotator.annotate(\n",
    "        scene=box_annotator.annotate(\n",
    "            scene=frame,\n",
    "            detections=results_det[\"detections\"],\n",
    "        ),\n",
    "        detections=results_det[\"detections\"],\n",
    "        labels=labels,\n",
    "    )\n",
    "    return annotated_frame \n",
    "\n",
    "pw_utils.process_video(source_path=SOURCE_VIDEO_PATH, target_path=TARGET_VIDEO_PATH, callback=callback, target_fps=5)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8e270f0f",
   "metadata": {},
   "source": [
    "### Copyright (c) Microsoft Corporation. All rights reserved.\n",
    "### Licensed under the MIT License."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "pytorch-wildlife",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
